package com.le.tester.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * createTime：2025-05-21 14:49
 * description：使用jwt
 */
public class TokenUtilTest {

    public static String salt = "test";

    //    gen token
    public static String genToken(String randomCode, String userUniqueCode) {
        Map<String, String> param = new HashMap<>();
        Date expireTime = DateTimeUtilFor8.toDate(LocalDateTime.now().plusMinutes(30L));

        JWTCreator.Builder builder = JWT.create();
        param.forEach(builder::withClaim);
//        gen sign JWT TOKEN的生成包含三个部分，header,payload,sign
        return JWT.create()
                .withHeader(new HashMap<>())
//                拼命向Java8及以上靠拢吧
                .withClaim("userId", 1)
                .withClaim("userRole", "admin")
                .withClaim("curTimeStamp", System.currentTimeMillis())
                .withExpiresAt(expireTime)
                .sign(Algorithm.HMAC256(salt));
    }

    //    解析token
    public static Map<String, Object> parseToken(String token) {
        Map<String, Object> map = new HashMap<>();

        DecodedJWT verify = JWT.require(Algorithm.HMAC256(salt)).build().verify(token);
        Claim userId = verify.getClaim("userId");
        Claim userRole = verify.getClaim("userRole");
        Claim curTimeStamp = verify.getClaim("curTimeStamp");
        map.put("userId", userId);
        map.put("userRole", userRole);
        map.put("curTimeStamp", curTimeStamp);
        return map;
    }

    public static void main(String[] args) {
        String s = TokenUtilTest.genToken("123", "147");
        System.out.println(s);
    }


}
